var path_to_ajax_backend = "/admin/js/ajax.php";
$(document).ready(function()
{
	$(".slide_next").live('click',function(){$(this).next().slideToggle("fast");});
	$("#tabs").tabs();
	var re_module_block_id = /to_module_(\d+)/;
	$(".module_vision").toggle(
		function()
		{
			module_id = $(this).attr("id").replace(re_module_block_id,"$1");
			$(this).removeClass("ui-icon-minus").addClass("ui-icon-plus");
			$("#admin_module_"+module_id).slideUp("fast");
		},
		function()
		{
			module_id = $(this).attr("id").replace(re_module_block_id,"$1");
			$(this).removeClass("ui-icon-plus").addClass("ui-icon-minus");
			$("#admin_module_"+module_id).slideDown("fast");
		}
	);
	$("#table_items").tableDnD({
		onDrop: function(table, row)
			{
				$.ajax({
					type: 'GET', // если хотите, сделайте POST
					data: $.tableDnD.serialize()+'&action=tableDnD&module=admin', // данные (для примера)
					url: path_to_ajax_backend, // url мы взяли из атрибута href
					success: function(msg)// делаем что-то по получению ответа
						{
							if(msg == 'ok')
							{
								$.facebox("It's ok!");
							}
							else
							{
								$.facebox(msg);
							}
						}, 
					error: function(){$.facebox('облом!')} // и в случае ошибки..
					});
			}
	});
	//TODO: jQuery->Designing elements
    $(".table_items tr:even").css("background","#E5E1DB");
    $(".table_items tr:odd").css("background","#F6F2EC");
    $(".add_item").click(
    function()
    {
        $("#item").slideToggle("fast");return false;
    });
    $('.add_adress_form').click(function()
    {
        addAdress();
    });
    $('.remove_adress_form').click(function()
    {
        delAdress();
    });
    $('.addContactForm').click(function()
    {
        ContactForm.addContactForm();
    });
    $('.remContactForm').click(function()
    {
        ContactForm.remContactForm();
    });
    $("#item_alias")
        .keyup(function(){generate_alias_hint()})
        .change(function(){generate_alias_hint()})
        .click(function(){generate_alias_hint()})
        .blur(function(){generate_alias_hint()});
});
function generate_alias_hint()
{
	$("#generated_alias_url").text(SITE_URL+Page.full_alias+$("#item_alias").attr("value")+'/');
	if($("#generated_alias_url").text() == SITE_URL+Page.full_alias+'/')
	{
        $("#generated_alias_url").text(SITE_URL+Page.full_alias+'... ваш алиас .../');
	}
}
function update(table,id,data,el_id,value,type)
{
    // Create new JsHttpRequest object.
    var req = new JsHttpRequest();
    
    // Code automatically called on load finishing.
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            //get errors from backend
            if(req.responseText)
            {
                alert(req.responseText);
            }
			//get data from backend		
            if (req.responseJS)
            {
                if(type=='checked')
                {
                    //change div innerHTML
                    document.getElementById(el_id).checked = 'yes';
                }
                else if(type=='value')
                {
                    //change div innerHTML
                    document.getElementById(el_id).value = value;
                }
                else if(type=='inner')
                {
                    //change div innerHTML
                    document.getElementById(el_id).innerHTML = value;
                }
                
            }
		}
    }
    // Prepare request object (automatically choose GET or POST).
    req.open(null, '/control/js/update.php', true);
	req.send({table:table,id:id,data:data});
}
/* TODO: function *delete*
 * Typical Used
 * <tag id="id" event="update('table','pole_id',{key:value[,key:value|*]},this.id,this.value|this.innerHTML,'checked|value|innerHTML')" [checked|value="value"|>value</tag>]
 * id		-	id of element
 * table	-	mysql's table
 * pole_id	-	UID of related pole in table
 * data		-	array of data to update
 * el_id	-	often are this.id, but could be id of another dom-element (must be specificated with document.getElementById())
 * value	-	changed value (display after event)
 * type		-	type of value to change (checked for radio and checkboxes, value for textboxes and innerHTML for divs)
 */
function del_item(type,clause)
{
    // Create new JsHttpRequest object.
    var req = new JsHttpRequest();
    
    // Code automatically called on load finishing.
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            //get errors from backend
            if(req.responseText)
            {
                alert(req.responseText);
            }
			//get data from backend		
            if (req.responseJS)
            {
            }
		}
    }
    // Prepare request object (automatically choose GET or POST).
    req.open(null, '/admin/js/ajax.php', true);
	req.send({type:type,clause:clause});
}
/**
 * функция show(id) Показывает и прячет элемент с id="id"
 * id - id тэга
 * @todo type - тип тэга, closed для тэгов, имеющих закрывающий, и odinary для одиночных тэгов
 */
function show(id)
{
    if(document.getElementById(id).style.display=='none')
    {
        document.getElementById(id).style.display='block';
    }
    else
    {
        document.getElementById(id).style.display='none';
    }
}
/**
 * функция add_razdel(el_id) меняет содержимое div'а, в котором находится форма для ввода данных, на пустую форму
 * со скрытым полем для добавления записей в БД
 */
function add_razdel(pid,el_id,module)
{
	    // Create new JsHttpRequest object.
    var req = new JsHttpRequest();
    switch(module)
    {
		case 'adm':
			adminflag='admin';
			break;
		case 'cont':
			adminflag='content';
			break;
		case 'cat':
			adminflag='category';
			break;
		case 'ctlg':
			adminflag='catalog';
			break;
		default:
			adminflag='0';
			break;
	}
    
    // Code automatically called on load finishing.
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            //get errors from backend
            if(req.responseText)
            {
                alert(req.responseText);
            }
			//get data from backend		
            if (req.responseJS)
            {
            	document.getElementById(el_id).innerHTML=req.responseJS.output;
            }
		}
    }
    // Prepare request object (automatically choose GET or POST).
    req.open(null, '/admin/js/add_razdel.php', true);
	req.send({pid:pid,adminflag:adminflag});

}
function recurse(parent,pid,type)
{
	document.getElementById(pid).innerHTML='<img src="/admin/i/windows/loading.gif" />'
	action='recurse';
	// Create new JsHttpRequest object.
    var req = new JsHttpRequest();
    
    // Code automatically called on load finishing.
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            //get errors from backend
            if(req.responseText)
            {
                alert(req.responseText);
            }
			//get data from backend		
            if (req.responseJS)
            {
            	document.getElementById(pid).innerHTML=req.responseJS.output;
            }
		}
    }
    // Prepare request object (automatically choose GET or POST).
    req.open(null, '/admin/js/ajax.php', true);
	req.send({parent:parent,action:action,type:type});
}
function upload_file(file,obj_id,item_id,type)
{
	action='upload_file';
	v('process').style.display='block';
	v('process').innerHTML+='<img src="/control/i/loading.gif">';
	v('fileshow').innerHTML='';
	// Create new JsHttpRequest object.
    var req = new JsHttpRequest();
    
    // Code automatically called on load finishing.
    req.onreadystatechange = function() {
    	//alert(req.readyState);
        if (req.readyState == 4) {
            //get errors from backend
            if(req.responseText)
            {
                v('process').innerHTML+=req.responseText;
                //alert(req.responseText);
            }
			//get data from backend		
            if (req.responseJS)
            {
            	//v('process').innerHTML='';
            	//v('process').style.display='none';
            	v('item').innerHTML=req.responseJS.output;
            	v('is_file_uploaded').innerHTML='файл загружен';
            	v('flag_is_file_uploaded').value='1';
				//v('item_id').value=req.responseJS.data.id;
            	//v('item_filesize').value=req.responseJS.data.filesize;
            }
		}
    }
    
    // Prepare request object (automatically choose GET or POST).
    req.open(null, path_to_ajax_backend, true);
	req.send({filename:file,obj_id:obj_id,id:item_id,type:type,action:action});
}
/** //TODO: del_item - удаление объекта (в т.ч. из БД)
**/
function del_item(type,clause,deleted_block)
{
	action='del_item';
	alert_block = 'alert';
	// Create new JsHttpRequest object.
    var req = new JsHttpRequest();
    
    // Code automatically called on load finishing.
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            //get errors from backend
            if(req.responseText)
            {
                $.facebox(req.responseText);
            }
			//get data from backend		
            if (req.responseJS)
            {
            	if(req.responseJS.ok=='1')
            	{
            		$("#"+deleted_block).remove();
            		$.facebox(req.responseJS.output);
            	}
            	else
            	{
            		$.facebox(req.responseJS.output);
            	}
            }
		}
    }
    // Prepare request object (automatically choose GET or POST).
    req.open(null, path_to_ajax_backend, true);
	req.send({type:type,clause_array:clause,action:action});
}
/** //TODO: archieve - изменение статуса объекта (display = 0)
**/
function archieve(type,clause,deleted_block)
{
	action='archieve';
	alert_block = 'alert';
	// Create new JsHttpRequest object.
    var req = new JsHttpRequest();
    
    // Code automatically called on load finishing.
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            //get errors from backend
            if(req.responseText)
            {
                $.facebox(req.responseText);
            }
			//get data from backend		
            if (req.responseJS)
            {
            	if(req.responseJS.ok=='1')
            	{
            		$("#"+deleted_block).remove();
            		$.facebox(req.responseJS.output);
            	}
            	else
            	{
            		$.facebox(req.responseJS.output);
            	}
            }
		}
    }
    // Prepare request object (automatically choose GET or POST).
    req.open(null, path_to_ajax_backend, true);
	req.send({type:type,clause_array:clause,action:action});
}
/** //TODO: unarchieve - изменение статуса объекта (display = 0)
**/
function unarchieve(type,clause,deleted_block)
{
	action='unarchieve';
	alert_block = 'alert';
	// Create new JsHttpRequest object.
    var req = new JsHttpRequest();
    
    // Code automatically called on load finishing.
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            //get errors from backend
            if(req.responseText)
            {
                $.facebox(req.responseText);
            }
			//get data from backend		
            if (req.responseJS)
            {
            	if(req.responseJS.ok=='1')
            	{
            		$("#"+deleted_block).remove();
            		$.facebox(req.responseJS.output);
            	}
            	else
            	{
            		$.facebox(req.responseJS.output);
            	}
            }
		}
    }
    // Prepare request object (automatically choose GET or POST).
    req.open(null, path_to_ajax_backend, true);
	req.send({type:type,clause_array:clause,action:action});
}
function del_item_attachment(type,clause,deleteType,attach_id)
{
	action='del_item_attachment';
	// Create new JsHttpRequest object.
    var req = new JsHttpRequest();
    // Code automatically called on load finishing.
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            //get errors from backend
            if(req.responseText)
            {
                $.facebox(req.responseText);
            }
			//get data from backend		
            if (req.responseJS)
            {
            	if(req.responseJS.ok == '1')
            	{
	            	$("#"+attach_id).remove();
		       		$.facebox(req.responseJS.output);
            	}
            	else
            	{
		       		$.facebox(req.responseJS.output);
            	}
            }
		}
    }
    // Prepare request object (automatically choose GET or POST).
    req.open(null, path_to_ajax_backend, true);
	req.send({type:type,clause_array:clause,deleteType:deleteType,action:action});
	
}
function addPhotoForm()
{
	action = "addPhotoForm";
	var items_num = $("#images_num").val();
	items_num++;
	var req = new JsHttpRequest();
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            //get errors from backend
            if(req.responseText)
            {
                $.facebox(req.responseText);
            }
			//get data from backend		
            if (req.responseJS)
            {
    			$('#images').append(req.responseJS.output);
    			$("#images_num").val(items_num);
            }
		}
    }
    // Prepare request object (automatically choose GET or POST).
    req.open(null, path_to_ajax_backend, true);
	req.send({items_num:items_num,action:action});
}
function delPhotoForm()
{
	var items_num = $("#images_num").val();
	if(items_num > 0)
	{
		deleting_div = "#image"+items_num;
		$(deleting_div).remove();
		items_num--;
		$("#images_num").val(items_num);
	}
}
function addVideoForm()
{
	action = "addVideoForm";
	var items_num = $("#videos_num").val();
	items_num++;
	var req = new JsHttpRequest();
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            //get errors from backend
            if(req.responseText)
            {
                $.facebox(req.responseText);
            }
			//get data from backend		
            if (req.responseJS)
            {
    			$('#videos').append(req.responseJS.output);
    			$("#videos_num").val(items_num);
            }
		}
    }
    // Prepare request object (automatically choose GET or POST).
    req.open(null, path_to_ajax_backend, true);
	req.send({items_num:items_num,action:action});
}
function delVideoForm()
{
	var items_num = $("#videos_num").val();
	if(items_num > 0)
	{
		items_num;
		deleting_div = "#video"+items_num;
		$(deleting_div).remove();
		items_num--;
		$("#videos_num").val(items_num);
	}
}
$(document).ready(function()
{
	$(".slide_trigger").click(function(){
		$("#item").slideToggle("slow");return false;
	});
});